package cn.edu.controller;

import cn.edu.entity.User;
import cn.edu.service.UserService;
import cn.edu.util.JwtUtil;
import cn.edu.vo.LoginVO;
import cn.edu.vo.ResultVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Mr.ma
 * @since 2022/11/23 15:30
 **/
@CrossOrigin
@RestController
@RequestMapping("/login")
@Api("用户登录控制")
public class LoginController {
    @Resource
    private UserService userService;

    @PostMapping("login")
    @ApiOperation("接收并处理用户登录请求")
    public ResultVO login(@RequestBody LoginVO loginVO){
        User user = userService.selectByNameAndPwd(loginVO);
        if (user != null){
            Map<String,Object> map = new HashMap<>(4);
            map.put("id",user.getId());
            map.put("username",user.getUsername());
            String token = JwtUtil.createToken(map);
            return new ResultVO(200,token,"登录成功");
        }
        return new ResultVO(500,null,"登录失败，用户名不存在或密码错误");
    }
}
